package cn.lzh.quartzadmin.cfg;

import cn.lzh.quartzadmin.biz.IQrtzAuthService;
import cn.lzh.quartzadmin.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    private IQrtzAuthService iQrtzAuthService;

    @Autowired
    public void setiQrtzAuthService(IQrtzAuthService iQrtzAuthService) {
        this.iQrtzAuthService = iQrtzAuthService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String reqUrl =  request.getRequestURI();
        String headerAppKey = request.getHeader("appKey");
        String headerAppSecret = request.getHeader("appSecret");
        System.err.println("reqUrl-->"+reqUrl);
        System.err.println("headerAppKey-->"+headerAppKey);
        System.err.println("headerAppSecret-->"+headerAppSecret);

        if (StringUtils.isEmpty(headerAppKey) || StringUtils.isEmpty(headerAppSecret)){
            throw new BaseException(5001,"reqHeader appKey or appSecret is null");
        }else if (!iQrtzAuthService.appKeyExistInDb(headerAppKey)) {
            throw new BaseException(5002, "appKey is not in system");
        }else if(!iQrtzAuthService.appSecretIsCorrect(headerAppKey, headerAppSecret)){
            throw new BaseException(5003, "appSecret is failed valid");
        }else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
